package com.atguigu.msmservice.controller;

import com.atguigu.msmservice.service.Msmservice;
import com.atguigu.msmservice.utils.RandomUtil;
import common.atguigu.commonutils.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/msmservice/msm")
@CrossOrigin
public class MsmController {
    @Autowired
    private Msmservice msmservice;

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    //发送短信的方法
    @GetMapping("code/{phone}")
    public R sendMsm(@PathVariable String phone){
        //1先去redis中获取验证码 有直接返回
        String code = redisTemplate.opsForValue().get(phone);
        if (!StringUtils.isEmpty(code)){
            return R.ok();
        }
        //2如果redis获取不到，进行阿里云发送
        //生成随机数
        code = RandomUtil.getFourBitRandom();
        //放入map中
        HashMap<String, Object> param = new HashMap<>();
        param.put("code",code);
        //调用service发送短信的方法
        boolean isSend = msmservice.send(param,phone);
        if (isSend){
            //发送成功把验证码放到redis中
            redisTemplate.opsForValue().set(phone,code,5, TimeUnit.MINUTES);
            return R.ok().message("发送成功");
        }else {
            return R.error().message("验证码发送失败");
        }

    }
}
